#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import common
import logging

from oriolus.docker.scripts.runner import RunnerError
from oriolus.pith.packets.packet import Status

class SetupError(common.CommandError):
    def __init__(self, message):
        common.CommandError.__init__(self, message)
        self.__message = message

    def __str__(self):
        return self.__message

class SetupCommand(common.Command):
    #exception handlings
    def __init__(self, script_runner, setup_status=Status.INSTALLING):
        self.__logger = logging.getLogger("SetupCommand")
        self.__setup_script_names = ("preinstall", "install", "postinstall")
        self.__runner = script_runner
        self.__setup_status = setup_status

    def execute(self, packet, args):
        self.__logger.info("Packet with name = %s will be installed", packet.name)
        setup_scripts = []
        for script_name in self.__setup_script_names:
            setup_scripts += [script for script in packet.scripts if script.name == script_name]
        #setup_scripts = [script.path for script in packet.scripts if script.name in self.__setup_script_names]
        self.__logger.debug("Execute install scripts")
        self.__runner.prepare()

        try:
            func = lambda x: self.__runner.run(x, args)
            map(func, setup_scripts)
        except RunnerError, ex:
            packet.status = Status.BAD
            message = "Setup error in packet %s has occurred: %s" % (packet.name, ex)
            if self.__logger.isEnabledFor(logging.DEBUG):
                self.__logger.exception(message)
            else:
                self.__logger.error(message)
            raise SetupError(message)
        else:
            packet.status = Status.status_map[self.__setup_status]
